<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="班组名称" prop="teamName">
        <el-input
          v-model.trim="queryParams.teamName"
          placeholder="请输入班组名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="班组负责人" prop="teamLeaderId">
        <el-input
          v-model.trim="queryParams.teamLeaderId"
          placeholder="请输入班组负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:team:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      max-height="440"
      v-loading="loading"
      :data="teamList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed="left" type="selection" width="55" align="center" />
      <el-table-column fixed="left" width="60" label="班组id" align="center" prop="teamId" />
      <el-table-column label="班组名称" align="center" prop="teamName" />
      <!-- <el-table-column label="班组类型" align="center" prop="teamType" /> -->
      <el-table-column label="班组负责人" align="center">
        <template slot-scope="scope">
          <span> {{ scope.row.teamLeaderName }} </span>-
          <span>{{ scope.row.teamLeaderPhone }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="角色状态" align="center" prop="status" /> -->
      <el-table-column width="170px" label="创建时间" align="center" prop="createTime" />
      <el-table-column width="170px" label="最后编辑时间" align="center" prop="updateTime" />
      <el-table-column width="100px" label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status == '0'"
            @change="changeStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="120px"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:team:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:team:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班组对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          :rules="[{ required: true, message: '请输入班组名称', trigger: 'blur' }]"
          label="班组名称"
          prop="teamName"
        >
          <el-input v-model="form.teamName" placeholder="请输入班组名称" />
        </el-form-item>
        <el-form-item
          :rules="[{ required: true, message: '请选择班组负责人', trigger: 'change' }]"
          label="班组负责人"
          required
          prop="teamLeaderId"
        >
          <div style="display: flex; gap: 20px; align-items: center">
            <span v-if="form.teamLeaderName">{{ form.teamLeaderName }}</span>
            <el-button type="text" @click="selectName1Visible = true">{{
              form.teamLeaderName ? "请重新选择" : "请选择"
            }}</el-button>
          </div>
        </el-form-item>
        <el-form-item required label="状态" prop="status">
          <el-switch
            v-model="form.status"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button @click="addRow" type="text" size="small"
            >新增一行</el-button
          >
          <el-table :data="form.teamRoleList">
            <el-table-column prop="roleId" label="角色（单选）" width="300">
              <template slot-scope="scope">
                <div style="display: flex; gap: 20px; align-items: center">
                  <span v-if="scope.row.roleId">{{ scope.row.roleName }}</span>
                  <el-button type="text" @click="selectRoleName(scope)">{{
                    scope.row.roleName ? "请重新选择" : "请选择"
                  }}</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="empIdLIst"
              label="员工（可多选）"
              width="500"
            >
              <template slot-scope="scope">
                <div style="display: flex; gap: 20px; align-items: center">
                  <div :key="e.id" v-for="(e, index) in scope.row.empIdLIst">
                    <span>{{ e.name }}</span>
                    <i
                      style="margin-left: 10px; cursor: pointer; color: red"
                      @click="deleteEmp(scope.$index, index)"
                      class="el-icon-close"
                    ></i>
                  </div>
                  <el-button type="text" @click="addEmpIdLIst(scope)"
                    >选择</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button @click="removeRole(scope)" type="text" size="small"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <SelectSalesmanDialog
      :dialogVisible="selectNameVisible"
      @onClose="selectNameVisible = false"
      :defauleUser="defauleUser"
      @onSubmit="selectName"
    ></SelectSalesmanDialog>
    <SelectNamemanDialog
      :multiple="false"
      width="850px"
      :dialogVisible="selectName1Visible"
      @onClose="selectName1Visible = false"
      @onSubmit="selectName"
    ></SelectNamemanDialog>

    <SelectRoleDialog
      :dialogVisible="selectRoleVisible"
      @onClose="selectRoleVisible = false"
      @onSubmit="selectRole"
    ></SelectRoleDialog>
  </div>
</template>

<script>
import {
  listTeam,
  getTeam,
  delTeam,
  addTeam,
  updateTeam,
} from "@/api/service/production/team";
import SelectSalesmanDialog from "@/components/SelectDialog/SelectSalesmanDialog";
import SelectRoleDialog from "@/components/SelectDialog/SelectRoleDialog";
export default {
  components: {
    SelectSalesmanDialog,
    SelectRoleDialog,
    SelectNamemanDialog: SelectSalesmanDialog,
  },
  name: "Team",
  data() {
    return {
      selectName1Visible: false,
      empIdIndex: -1,
      roleIndex: -1,
      selectRoleVisible: false,
      selectNameVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班组表格数据
      teamList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamName: null,
        teamType: null,
        teamLeaderId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  computed: {
    defauleUser() {
      if (this.form.teamRoleList && this.empIdIndex != -1) {
        return this.form.teamRoleList[this.empIdIndex].empIdLIst.map(
          (item) => ({
            userId: item.id,
            nickName: item.name,
          })
        );
      }
      return [];
    },
  },
  methods: {
    // 开关
    async changeStatus(item) {
      const form = { ...item };
      if (item.status != "0") {
        form.status = 0;
        await updateTeam(form);
        this.$modal.msgSuccess("修改成功");
        item.status = form.status;
        return;
      } else {
        this.$modal
          .confirm(
            "停用后，将导致今天及以后的所有此班组的排班失效，你确定停用吗？"
          )
          .then(function () {
            form.status = 1;
            return updateTeam(form);
          })
          .then(() => {
            //this.getList();
            this.$modal.msgSuccess("修改成功");
            item.status = form.status;
          })
          .catch(() => {});
      }
    },
    addEmpIdLIst(scope) {
      this.empIdIndex = scope.$index;
      this.selectNameVisible = true;
    },
    selectRole(row) {
      this.form.teamRoleList[this.roleIndex].roleId = row.roleId;
      this.form.teamRoleList[this.roleIndex].roleName = row.roleName;
    },
    deleteEmp(mainIndex, subIndex) {
      this.form.teamRoleList[mainIndex].empIdLIst.splice(subIndex, 1);
    },
    removeRole(scope) {
      this.form.teamRoleList.splice(scope.$index, 1);
    },
    selectRoleName(scope) {
      this.roleIndex = scope.$index;
      this.selectRoleVisible = true;
    },
    addRow() {
      this.form.teamRoleList.push({
        roleId: null,
        roleName: null,
        empIdLIst: [],
      });
    },
    selectName(arr) {
      if (this.empIdIndex == -1) {
        this.form.teamLeaderId = arr.userId;
        this.form.teamLeaderName = arr.nickName;
      } else {
        this.form.teamRoleList[this.empIdIndex].empIdLIst = arr.map((item) => ({
          id: item.userId,
          name: item.nickName,
        }));
      }
      this.empIdIndex = -1;
    },
    /** 查询班组列表 */
    getList() {
      this.loading = true;
      listTeam(this.queryParams).then((response) => {
        this.teamList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        teamId: null,
        teamName: null,
        teamType: null,
        teamLeaderId: null,
        teamRoleList: [],
        status: "1",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.teamId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增班组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teamId = row.teamId || this.ids;
      getTeam(teamId).then((response) => {
        response.data.teamRoleList.forEach((item) => {
          item.empIdLIst = item.teamEmpList.map((t) => ({
            id: t.empId,
            name: t.empName,
          }));
        });

        this.form = response.data;
        this.open = true;
        this.title = "修改班组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const subForm = JSON.parse(JSON.stringify(this.form));
      subForm.teamRoleList.forEach((item) => {
        item.empIdLIst = item.empIdLIst.map((e) => e.id);
      });

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.teamId != null) {
            updateTeam(subForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeam(subForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const teamIds = row.teamId || this.ids;
      this.$modal
        .confirm(
          "删除后，将导致今天及以后的所有此班组的排班失效，你确定删除吗？"
        )
        .then(function () {
          return delTeam(teamIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/team/export",
        {
          ...this.queryParams,
        },
        `team_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
